<template>
	<view class="contract-container">

		<!-- 顶部导航栏 -->
		<view class="nav-header">
			<view class="nav-title">
				<view class="title-text">租客合同</view>
				<view class="nav-actions">
					<view class="search-icon">
						<uni-icons type="search" size="20" @click="showSearch"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 添加搜索容器 -->
		<view class="search-container" v-if="showSearchView">
			<!-- 搜索头部 -->
			<view class="search-header">
				<uni-search-bar v-model="searchText" :placeholder="searchPlaceholder" @confirm="handleSearch"
					@clear="clearSearch" @cancel="hideSearch" cancelButton="auto" clearButton="always" :focus="true"
					class="custom-search-bar"></uni-search-bar>
			</view>

			<!-- 标签栏 -->
			<view class="tag-bar search-tag-bar">
				<scroll-view scroll-x class="tag-scroll" :show-scrollbar="false">
					<uni-tag v-for="(tag, index) in searchFilterTags" :key="index" :text="tag"
						:type="currentSearchTag === index ? 'primary' : 'default'" :inverted="false" :custom-style="{
							backgroundColor: currentSearchTag === index ? '' : '#f5f5f5',
							color: currentSearchTag === index ? '' : '#666',
							borderWidth: '0',
							marginRight: '16rpx',
							display: 'inline-block'
						}" @click="switchSearchTag(index)" class="search-tag-item"></uni-tag>
				</scroll-view>
			</view>
		</view>


		<!-- 筛选条件区域 -->
		<filter-bar :filters="['department', 'contractStatus', 'filter']" :filter-data="filterData"
			@filter-change="handleFilterChange" />


		<!-- 合同列表 - 添加固定高度容器 -->
		<scroll-view scroll-y class="scroll-view" :show-scrollbar="false" @scrolltolower="loadMore" refresher-enabled
			:refresher-triggered="isTriggered" :refresher-text="refreshText" @refresherrefresh="onRefresh"
			@refresherpulling="onPullingDown" virtual-list>
			<view class="contract-list">
				<view class="contract-item" v-for="(item, index) in contractList" :key="index">
					<view class="status-tag">在租中</view>
					<view class="contract-content">
						<view class="contract-info">
							<view class="contract-title">{{ item.title }}</view>
							<view class="contract-detail">
								<text class="date">{{ item.start_date }} 至 {{ item.end_date }}</text>
								<text class="tenant">| {{ item.tenant }}</text>
							</view>
							<view class="contract-status">
								<text class="days-left">{{ item.days_left }}天后离店</text>
							</view>
						</view>
						<view class="contract-action">
							<view class="bind-btn" @click="inviteBind(item)">
								<text>邀请绑定</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 加载更多 -->
				<view class="load-more">
					<uni-load-more :status="loadMoreStatus"></uni-load-more>
				</view>
			</view>
		</scroll-view>
		<!-- 浮动底部统计信息 -->
		<view class="floating-statistics">
			<text>1</text>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			// 添加筛选数据配置
			filterData: {
				department: [
					{
						value: 'dept1',
						label: '总部',
						children: [
							{ value: 'user1', label: '张三' },
							{ value: 'user2', label: '李四' }
						]
					},
					{
						value: 'dept2',
						label: '分部',
						children: [
							{ value: 'user3', label: '王五' },
							{ value: 'user4', label: '赵六' }
						]
					}
				],
				contractStatus: [
					{ value: 'all', label: '不限' },
					{ value: 'renting', label: '在租中' },
					{ value: 'moving_in', label: '将搬入' },
					{ value: 'moved_out_paid', label: '已退组(已结账)' },
					{ value: 'moved_out_unpaid', label: '已退组(未结账)' },
					{ value: 'pending_confirmation', label: '待租客确认' }
				],
				filter: [
					{
						title: '房间状态',
						type: 'roomStatus',
						options: [
							{ value: 'available', label: '可租' },
							{ value: 'reserved', label: '已预订' },
							{ value: 'occupied', label: '已入住' }
						]
					},
					{
						title: '租客状态',
						type: 'tenantStatus',
						options: [
							{ value: 'normal', label: '正常' },
							{ value: 'arrears', label: '欠费' },
							{ value: 'expired', label: '已到期' }
						]
					}
				]
			},
			contractList: [
				{
					title: '光谷青年城9号1单元3214·1',
					department: '总部 | 杨子维',
					start_date: '2023-08-23',
					end_date: '2024-02-22',
					tenant: '杨子维',
					days_left: 1,
					tag: ''
				},
				{
					title: '明珠花园5号3单元701·1',
					department: '总部 | 庞楚杨',
					start_date: '2024-02-23',
					end_date: '2025-02-22',
					tenant: '庞楚杨',
					days_left: 1,
					tag: ''
				},
				{
					title: '光谷悦城9号2单元1704·2',
					department: '总部 | 刘幸宇',
					start_date: '2024-02-24',
					end_date: '2025-02-23',
					tenant: '刘幸宇',
					days_left: 2,
					tag: ''
				},
				{
					title: '保利华都28号1单元3003·3',
					department: '总部 | 陈红林',
					start_date: '2023-11-24',
					end_date: '2024-02-23',
					tenant: '陈红林',
					days_left: 2,
					tag: ''
				},
				{
					title: '芭比伦堡6号4单元102·2',
					department: '总部 | 瞿田',
					start_date: '2023-11-25',
					end_date: '2024-02-24',
					tenant: '瞿田',
					days_left: 3,
					tag: ''
				},
				{
					title: '中建大公馆16号2单元2202·2',
					department: '总部 | 袁友盟',
					start_date: '2023-07-25',
					end_date: '2024-02-24',
					tenant: '袁友盟',
					days_left: 3,
					tag: ''
				},
				{
					title: '金地中心城6号2单元204·3',
					department: '总部 | 史清玉',
					start_date: '2023-07-25',
					end_date: '2024-02-24',
					tenant: '史清玉',
					days_left: 3,
					tag: ''
				}
			],
			showSearchView: false,
			searchText: '',
			searchPlaceholder: "地址/房源编号/租客/合同编号",
			currentSearchTag: 0,
			searchFilterTags: ['综合', '地址', '房源编号', '租客', '合同编号'],
			isLoading: false,
			isTriggered: false,
			loadMoreStatus: 'more', // 添加这个状态
			noMore: false,
			page: 1,
			pageSize: 10
		}
	},
	onLoad() {
		this.page = 1;
		// 页面加载时获取合同数据
		this.getContractList();
	},
	// 在每个TabBar页面的onShow方法中添加
	onShow() {
		uni.$emit('tabChange');
	},
	methods: {
		goBack() {
			uni.navigateBack();
		},
		/**
 * 显示搜索容器
 */
		showSearch() {
			this.showSearchView = true;
			this.searchText = '';
		},
		/**
		 * 隐藏搜索容器
		 */
		hideSearch() {
			this.showSearchView = false;
		},
		/**
		 * 清除搜索内容
		 */
		clearSearch() {
			this.searchText = '';
			// 重置筛选结果，显示所有数据
			this.refreshList();
		},
		/**
		 * 处理搜索提交
		 */
		handleSearch() {
			if (!this.searchText.trim()) return;

			// 根据搜索文本和当前选中的标签筛选数据
			const searchText = this.searchText.toLowerCase();
			const searchType = this.currentSearchTag;

			// 根据搜索类型和文本筛选数据
			this.filterContractData(searchText, searchType);
		},
		/**
		 * 切换搜索标签
		 * @param {number} index - 标签索引
		 */
		switchSearchTag(index) {
			this.currentSearchTag = index;
			// 根据标签类型更新搜索框占位符
			switch (index) {
				case 0:
					this.searchPlaceholder = "地址/房源编号/租客/合同编号";
					break;
				case 1:
					this.searchPlaceholder = "请输入地址关键词";
					break;
				case 2:
					this.searchPlaceholder = "请输入房源编号";
					break;
				case 3:
					this.searchPlaceholder = "请输入租客姓名或手机号";
					break;
				case 4:
					this.searchPlaceholder = "请输入合同编号";
					break;
				default:
					this.searchPlaceholder = "地址/房源编号/租客/合同编号";
			}
			// 如果已有搜索文本，则重新搜索
			if (this.searchText) {
				this.handleSearch();
			}
		},
		/**
		 * 筛选合同数据
		 * @param {string} searchText - 搜索文本
		 * @param {number} searchType - 搜索类型：0-综合, 1-地址, 2-房源编号, 3-租客, 4-合同编号
		 */
		filterContractData(searchText, searchType) {
			// 根据搜索类型和文本筛选数据
			console.log(`搜索类型: ${this.searchFilterTags[searchType]}, 搜索文本: ${searchText}`);

			// 重置页码
			this.page = 1;
			this.noMore = false;

			// 模拟筛选逻辑
			// 实际应用中，这里应该根据searchType和searchText过滤contractList
			// 或者发送请求到服务器获取筛选后的数据

			// 示例筛选逻辑
			let filteredList = [];

			switch (searchType) {
				case 0: // 综合
					filteredList = this.contractList.filter(item =>
						item.title.toLowerCase().includes(searchText) ||
						item.tenant.toLowerCase().includes(searchText)
					);
					break;
				case 1: // 地址
					filteredList = this.contractList.filter(item =>
						item.title.toLowerCase().includes(searchText)
					);
					break;
				case 2: // 房源编号
					// 假设房源编号在title中
					filteredList = this.contractList.filter(item =>
						item.title.toLowerCase().includes(searchText)
					);
					break;
				case 3: // 租客
					filteredList = this.contractList.filter(item =>
						item.tenant.toLowerCase().includes(searchText)
					);
					break;
				case 4: // 合同编号
					// 假设合同编号是一个单独的字段，这里仅作示例
					filteredList = this.contractList.filter(item =>
						(item.contract_id || '').toLowerCase().includes(searchText)
					);
					break;
			}

			// 更新筛选后的列表
			this.contractList = filteredList;

			// 如果没有数据，显示提示
			if (filteredList.length === 0) {
				this.loadMoreStatus = 'noMore';
				uni.showToast({
					title: '没有找到相关数据',
					icon: 'none'
				});
			} else {
				this.loadMoreStatus = 'more';
			}
		},
		/**
		 * 刷新列表
		 */
		refreshList() {
			this.page = 1;
			this.noMore = false;
			this.loadMoreStatus = 'more';
			this.getContractList(true);
		},
		// 下拉刷新
		onRefresh() {
			if (this.isLoading) return;
			this.isTriggered = true;
			this.page = 1;
			this.noMore = false;

			this.getContractList(true).then(() => {
				this.isTriggered = false;
				uni.showToast({
					title: '刷新成功',
					icon: 'none'
				});
			});
		},
		// 上拉加载更多
		loadMore() {
			if (!this.isLoading && !this.noMore) {
				this.page++;
				this.getContractList();
			}
		},
		getContractList(refresh = false) {
			// 获取合同列表数据
			this.isLoading = true;
			this.loadMoreStatus = 'loading';

			return new Promise((resolve) => {
				setTimeout(() => {
					// 模拟新数据，使用固定格式
					const newData = Array.from({ length: this.pageSize }, (_, i) => ({
						title: `光谷青年城${(this.page - 1) * this.pageSize + i + 1}号`,
						department: '总部',
						start_date: '2024-02-24',
						end_date: '2025-02-23',
						tenant: `租客${(this.page - 1) * this.pageSize + i + 1}`,
						days_left: Math.floor(Math.random() * 30) + 1,
						tag: ''
					}));

					if (refresh) {
						this.contractList = newData;
					} else {
						this.contractList = [...this.contractList, ...newData];
					}

					this.isLoading = false;
					this.noMore = this.page >= 3; // 模拟3页后没有更多数据
					this.loadMoreStatus = this.noMore ? 'noMore' : 'more';
					resolve();
				}, 1000);
			});
		},
		inviteBind(item) {
			// 跳转到邀请绑定页面
			uni.navigateTo({
				url: `/pages/guide/index?contract_id=${item.id}&type=bind`
			});
		}
	}
}
</script>

<style lang="scss" scoped>
.contract-container {
	height: 100%;
	display: flex;
	flex-direction: column;
	background-color: #f5f5f5;
	position: relative;
	/* 保留底部安全区域 */
	padding-bottom: env(safe-area-inset-bottom);
}

// 添加搜索容器样式
.search-container {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	z-index: 2000;
	background-color: #fff;
}

.search-header {
	padding: 10rpx 0;
	background-color: #fff;

	// 自定义uni-search-bar样式
	:deep(.custom-search-bar) {
		.uni-searchbar {
			padding: 10rpx 20rpx;
		}

		.uni-searchbar__box {
			border-radius: 36rpx;
			background-color: #f5f5f5;
		}

		.uni-searchbar__cancel {
			font-size: 28rpx;
			color: #333;
		}
	}
}

.search-tag-bar {
	background-color: #fff;
	padding: 0 0 20rpx 0;
	border-bottom: 1rpx solid #eee;

	.tag-scroll {
		white-space: nowrap;
		width: 100%;
		padding: 0 20rpx;
		box-sizing: border-box;

		&::-webkit-scrollbar {
			display: none;
		}
	}

	// 自定义uni-tag样式
	:deep(.search-tag-item) {
		margin-right: 20rpx;

		&:last-child {
			margin-right: 20rpx;
		}
	}
}

.scroll-view {

	flex: 1;
	/* 使用flex布局，让内容区域自动填充剩余空间 */
	overflow: auto;
	/* 内容超出时可滚动 */
	padding-top: 0;
	/* 不再需要为fixed元素预留空间 */
}

.contract-list {
	padding: 0 20rpx;
}

.contract-item {
	background-color: #fff;
	margin: 20rpx 0;
	border-radius: 12rpx;
	overflow: visible;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	padding: 24rpx;
	transition: transform 0.2s ease;
	position: relative;

	&:active {
		transform: scale(0.98);
	}

	&::after {
		display: none;
	}
}

.contract-content {
	display: flex;
	flex-direction: column;
	position: relative;
	min-height: 160rpx;

	.contract-info {
		flex: 1;
		min-width: 0;
	}

	.contract-title {
		font-size: 28rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 16rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		line-height: 1.4;
	}

	.contract-detail {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 16rpx;
		line-height: 1.5;
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;

		text {
			display: inline-flex;
			align-items: center;
			white-space: nowrap;

			&.department {
				color: #1890ff;
				font-weight: 500;
				font-size: 22rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.call-btn {
					display: inline-flex;
					align-items: center;
					margin-left: 8rpx;
					padding: 2rpx 8rpx;
					border-radius: 4rpx;
					background-color: rgba(24, 144, 255, 0.1);

					text {
						color: #1890ff;
						font-size: 24rpx;
						margin-left: 4rpx;
					}
				}
			}

			&.date,
			&.tenant {
				color: #666;
				font-size: 22rpx;
			}
		}
	}

	.contract-status {
		font-size: 24rpx;
		color: #999;
		line-height: 1.4;
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		gap: 16rpx;

		text {
			display: inline-block;

			&.days-left {
				color: #ff6666;
				background-color: #f5f5f5;
				padding: 4rpx 12rpx;
				border-radius: 4rpx;
				font-size: 20rpx;
			}
		}
	}
}

.contract-action {
	position: absolute;
	right: 0;
	bottom: 0;

	.bind-btn {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		padding: 4rpx 12rpx;
		border: 1rpx solid #999;
		border-radius: 8rpx;

		text {
			color: #666;
			font-size: 20rpx;
		}
	}
}

.status-tag {
	position: absolute;
	top: 24rpx;
	right: 0;
	padding: 2rpx 8rpx;
	background-color: #13c2c2;
	color: #fff;
	font-size: 20rpx;
	border-radius: 8rpx 0 0 8rpx;
	line-height: 1.4;
}

.nav-header {
	background-color: #fff;
	padding: 20rpx 30rpx;
	height: 80rpx;
	box-sizing: border-box;
	position: sticky;
	top: var(--window-top);
	z-index: 1000;

	.nav-title {
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;

		.title-text {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}

		.nav-actions {
			display: flex;
			align-items: center;
			position: absolute;
			right: 0;
			top: 50%;
			transform: translateY(-50%);

			.search-icon {
				margin-left: 30rpx;
				width: 44rpx;
				height: 44rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}
}

.floating-statistics {
	position: fixed;
	bottom: 120rpx;
	left: 50%;
	transform: translateX(-50%);
	background-color: rgba(80, 80, 80, 0.8);
	color: #ffffff;
	padding: 6rpx;
	border-radius: 6rpx;
	/* 减小圆角到最小 */
	font-size: 24rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
	z-index: 9999;
	display: flex;
	align-items: center;
	justify-content: center;
	line-height: 1.2;
	white-space: nowrap;
}
</style>